package me.maiz.lab.batchdemo.batch;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.BeanCopier;
import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import me.maiz.lab.batchdemo.batch.domain.UserOrderData;
import me.maiz.lab.batchdemo.entity.User;
import org.springframework.batch.item.ItemProcessor;

import java.util.stream.Collectors;

@Slf4j
public class UserCreditCalcProcessor implements ItemProcessor<UserOrderData, User> {

    @Override
    public User process(UserOrderData item) throws Exception {

        log.info("开始计算用户评分：{}",item);
        User user = BeanUtil.copyProperties(item, User.class);

        double orderTotalAmount = item.getOrder().stream().collect(Collectors.summarizingDouble(o -> o.getTotalAmount())).getSum();
        double credit =calcCredit(orderTotalAmount,user);
        int level = calcLevel(credit);

        user.setCredit(user.getCredit()+credit);
        user.setLevel(user.getLevel()+level);
        return user;
    }

    private int calcLevel(double credit) {
        return (int) (credit/1000);
    }

    private double calcCredit(double orderTotalAmount, User user) {
        if(orderTotalAmount==0){
            int noConsumeWeeks = user.getNoConsumeWeeks();
            int times = noConsumeWeeks/4;
            double mod = noConsumeWeeks- noConsumeWeeks/4;
            user.setNoConsumeWeeks(noConsumeWeeks+1);

            return (times*1+mod*0.1)*-1;
        }


        if(orderTotalAmount<1000){
            double v = orderTotalAmount % 100;
            int times = (int) (orderTotalAmount/100);
            int finalTimes = v==0?times:(int)(times+Math.round(v));
            return finalTimes*0.1;
        }

        if(orderTotalAmount<10000){
            double v = orderTotalAmount % 1000;
            int times = (int) (orderTotalAmount/1000);
            int finalTimes = v==0?times:(int)(times+Math.round(v));
            return finalTimes*10;
        }
        if(orderTotalAmount<100000){
            double v = orderTotalAmount % 10000;
            int times = (int) (orderTotalAmount/10000);
            int finalTimes = v==0?times:(int)(times+Math.round(v));
            return finalTimes*100;
        }

        double v = orderTotalAmount % 100000;
        int times = (int) (orderTotalAmount/100000);
        int finalTimes = v==0?times:(int)(times+Math.round(v));
        return finalTimes*1000;

    }
}
